<template>
  <div class="travel-expense-page">
    <div class="content-area">
      <van-form @submit="onSubmit">
        <!-- 基本信息 -->
        <van-cell-group inset title="基本信息">
          <!-- 关联出差申请 -->
          <van-field
            readonly
            clickable
            name="travelApply"
            :model-value="selectedTravel ? `${selectedTravel.destination}(${selectedTravel.startDate} - ${selectedTravel.endDate})` : ''"
            label="关联出差"
            placeholder="选择关联的出差申请"
            @click="showTravelPopup = true"
            :rules="[{ required: true, message: '请选择关联的出差申请' }]"
          />
          
          <!-- 报销事由 -->
          <van-field
            v-model="formData.reason"
            label="报销事由"
            type="textarea"
            placeholder="请输入报销事由"
            rows="2"
            autosize
            :rules="[{ required: true, message: '请填写报销事由' }]"
          />
          
          <!-- 报销总额 -->
          <van-field
            v-model="totalExpense"
            label="报销总额"
            type="number"
            readonly
            right-icon="info-o"
            @click-right-icon="showTip('报销总额将根据各项费用明细自动计算')"
          />
        </van-cell-group>
        
        <!-- 费用明细 -->
        <van-cell-group inset title="费用明细">
          <!-- 交通费 -->
          <van-cell title="交通费" is-link @click="showExpenseEditor('transportation')">
            <template #right-icon>
              <span class="expense-amount">{{ formData.transportation || '0.00' }} 元</span>
            </template>
          </van-cell>
          
          <!-- 住宿费 -->
          <van-cell title="住宿费" is-link @click="showExpenseEditor('accommodation')">
            <template #right-icon>
              <span class="expense-amount">{{ formData.accommodation || '0.00' }} 元</span>
            </template>
          </van-cell>
          
          <!-- 餐饮费 -->
          <van-cell title="餐饮费" is-link @click="showExpenseEditor('meals')">
            <template #right-icon>
              <span class="expense-amount">{{ formData.meals || '0.00' }} 元</span>
            </template>
          </van-cell>
          
          <!-- 其他费用 -->
          <van-cell title="其他费用" is-link @click="showExpenseEditor('others')">
            <template #right-icon>
              <span class="expense-amount">{{ formData.others || '0.00' }} 元</span>
            </template>
          </van-cell>
        </van-cell-group>
        
        <!-- 附件上传 -->
        <van-cell-group inset title="票据附件">
          <div class="invoice-selector">
            <van-button type="primary" size="small" plain icon="search" @click="showInvoiceSelector = true">从发票库选择</van-button>
            <div class="selected-invoices" v-if="selectedInvoices.length > 0">
              <div class="invoice-tag" v-for="invoice in selectedInvoices" :key="invoice.id">
                <van-tag closeable @close="removeSelectedInvoice(invoice.id)">
                  {{ invoice.title }} (¥{{ invoice.amount }})
                </van-tag>
              </div>
            </div>
          </div>
          <van-uploader
            v-model="uploadedFiles"
            :max-count="9"
            :max-size="5 * 1024 * 1024"
            :before-read="beforeRead"
            :after-read="afterRead"
            @delete="deleteFile"
            multiple
          />
          <div class="upload-tips">
            请上传发票、行程单等报销凭证，最多9个文件，每个文件不超过5MB，或从发票库选择已有发票
          </div>
        </van-cell-group>
        
        <!-- 提交按钮 -->
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交报销
          </van-button>
        </div>
      </van-form>
      
      <!-- 关联出差申请选择弹窗 -->
      <van-popup v-model:show="showTravelPopup" position="bottom" round>
        <div class="popup-header">
          <div class="popup-title">选择关联出差申请</div>
          <van-icon name="cross" @click="showTravelPopup = false" />
        </div>
        <van-radio-group v-model="selectedTravelId">
          <van-cell-group>
            <van-cell 
              v-for="travel in availableTravels" 
              :key="travel.id" 
              :title="travel.destination" 
              :label="`${travel.startDate} - ${travel.endDate}`"
              clickable 
              @click="selectedTravelId = travel.id"
            >
              <template #right-icon>
                <van-radio :name="travel.id" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
        <div class="popup-footer">
          <van-button type="primary" block round @click="confirmTravel">确认选择</van-button>
        </div>
      </van-popup>
      
      <!-- 费用明细编辑弹窗 -->
      <van-popup v-model:show="showExpensePopup" position="bottom" round>
        <div class="popup-header">
          <div class="popup-title">{{ currentExpenseType === 'transportation' ? '交通费' : 
                                     currentExpenseType === 'accommodation' ? '住宿费' : 
                                     currentExpenseType === 'meals' ? '餐饮费' : '其他费用' }}</div>
          <van-icon name="cross" @click="showExpensePopup = false" />
        </div>
        <div class="expense-editor">
          <van-field
            v-model="currentExpenseAmount"
            type="number"
            label="金额"
            placeholder="请输入金额"
          />
          <van-field
            v-model="currentExpenseNote"
            type="textarea"
            label="说明"
            placeholder="请输入费用说明"
            rows="3"
            autosize
          />
        </div>
        <div class="popup-footer">
          <van-button type="primary" block round @click="confirmExpense">确认</van-button>
        </div>
      </van-popup>
      
      <!-- 发票选择弹窗 -->
      <van-popup v-model:show="showInvoiceSelector" position="bottom" round>
        <div class="popup-header">
          <div class="popup-title">选择关联发票</div>
          <van-icon name="cross" @click="showInvoiceSelector = false" />
        </div>
        <div class="invoice-filter">
          <van-search v-model="invoiceSearchText" placeholder="搜索发票" />
          <div class="filter-actions">
            <van-dropdown-menu>
              <van-dropdown-item v-model="invoiceFilterStatus" :options="invoiceStatusOptions" />
            </van-dropdown-menu>
            <van-checkbox v-model="selectAll" @click="toggleSelectAll">全选</van-checkbox>
          </div>
        </div>
        <div class="invoice-list">
          <van-checkbox-group v-model="selectedInvoiceIds">
            <van-cell 
              v-for="invoice in filteredInvoices" 
              :key="invoice.id" 
            >
              <template #icon>
                <div class="invoice-checkbox-wrapper" @click.stop="toggleInvoiceSelection(invoice.id)">
                  <van-checkbox :name="invoice.id" />
                </div>
              </template>
              <template #title>
                <div class="invoice-content" @click="toggleInvoiceSelection(invoice.id)">
                  <div class="invoice-title">{{ invoice.title }}</div>
                  <div class="invoice-label">发票代码: {{ invoice.code }} · {{ invoice.date }}</div>
                </div>
              </template>
              <template #right-icon>
                <div class="invoice-amount">¥{{ formatAmount(invoice.amount) }}</div>
              </template>
            </van-cell>
          </van-checkbox-group>
          <van-empty v-if="filteredInvoices.length === 0" description="未找到符合条件的发票" />
        </div>
        <div class="invoice-selection-summary" v-if="selectedInvoiceIds.length > 0">
          <div class="summary-content">
            已选择 <span class="highlight">{{ selectedInvoiceIds.length }}</span> 张发票，
            金额合计 <span class="highlight">¥{{ formatAmount(totalSelectedAmount) }}</span>
          </div>
        </div>
        <div class="popup-footer">
          <van-button type="primary" block round @click="confirmInvoiceSelection">确认选择({{ selectedInvoiceIds.length }})</van-button>
        </div>
      </van-popup>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { NavBar, Form, Field, CellGroup, Cell, Button, Uploader, Popup, RadioGroup, Radio, Icon, Toast, Search, DropdownMenu, DropdownItem, Checkbox, CheckboxGroup, Empty, Tag } from 'vant'
import 'vant/es/toast/style'

export default {
  name: 'FinanceTravelExpense',
  components: {
    vanNavBar: NavBar,
    vanForm: Form,
    vanField: Field,
    vanCellGroup: CellGroup,
    vanCell: Cell,
    vanButton: Button,
    vanUploader: Uploader,
    vanPopup: Popup,
    vanRadioGroup: RadioGroup,
    vanRadio: Radio,
    vanIcon: Icon,
    vanSearch: Search,
    vanDropdownMenu: DropdownMenu,
    vanDropdownItem: DropdownItem,
    vanCheckbox: Checkbox,
    vanCheckboxGroup: CheckboxGroup,
    vanEmpty: Empty,
    vanTag: Tag
  },
  setup() {
    const router = useRouter()
    
    // 表单数据
    const formData = reactive({
      travelId: null,
      reason: '',
      transportation: '',
      accommodation: '',
      meals: '',
      others: '',
      attachments: [],
      invoices: [] // 存储关联的发票ID
    })
    
    // 附件上传相关
    const uploadedFiles = ref([])
    
    // 关联出差选择相关
    const showTravelPopup = ref(false)
    const selectedTravelId = ref(null)
    
    // 费用明细编辑相关
    const showExpensePopup = ref(false)
    const currentExpenseType = ref('')
    const currentExpenseAmount = ref('')
    const currentExpenseNote = ref('')
    
    // 发票选择相关
    const showInvoiceSelector = ref(false)
    const invoiceSearchText = ref('')
    const invoiceFilterStatus = ref('all')
    const selectedInvoiceIds = ref([])
    const selectedInvoices = ref([])
    const checkboxRefs = ref([])
    const selectAll = ref(false)
    
    const invoiceStatusOptions = [
      { text: '全部发票', value: 'all' },
      { text: '已验证', value: 'verified' },
      { text: '待使用', value: 'unused' }
    ]
    
    // 模拟发票数据
    const availableInvoices = ref([
      {
        id: 1,
        title: '某航空公司',
        code: '044001900311',
        date: '2023-10-15',
        type: 'electronic',
        status: 'verified',
        amount: 1580.00,
        imageUrl: 'https://example.com/invoice1.jpg'
      },
      {
        id: 2,
        title: '某餐饮有限公司',
        code: '044001900312',
        date: '2023-10-12',
        type: 'electronic',
        status: 'verified',
        amount: 328.50,
        imageUrl: 'https://example.com/invoice2.jpg'
      },
      {
        id: 3,
        title: '某酒店有限公司',
        code: '044001900313',
        date: '2023-10-10',
        type: 'vat-normal',
        status: 'verified',
        amount: 1260.00,
        imageUrl: 'https://example.com/invoice3.jpg'
      },
      {
        id: 4,
        title: '高铁票',
        code: '044001900314',
        date: '2023-10-08',
        type: 'electronic',
        status: 'verified',
        amount: 620.00,
        imageUrl: 'https://example.com/invoice4.jpg'
      },
      {
        id: 5,
        title: '出租车票',
        code: '044001900315',
        date: '2023-10-12',
        type: 'paper',
        status: 'verified',
        amount: 76.50,
        imageUrl: 'https://example.com/invoice5.jpg'
      },
      {
        id: 6,
        title: '某科技有限公司',
        code: '044001900316',
        date: '2023-10-11',
        type: 'vat-special',
        status: 'verified',
        amount: 450.00,
        imageUrl: 'https://example.com/invoice6.jpg'
      }
    ])
    
    // 根据筛选条件过滤发票
    const filteredInvoices = computed(() => {
      let result = [...availableInvoices.value]
      
      // 根据状态筛选
      if (invoiceFilterStatus.value !== 'all') {
        result = result.filter(invoice => invoice.status === invoiceFilterStatus.value)
      }
      
      // 根据搜索文本筛选
      if (invoiceSearchText.value) {
        const searchText = invoiceSearchText.value.toLowerCase()
        result = result.filter(invoice => 
          invoice.title.toLowerCase().includes(searchText) || 
          invoice.code.includes(searchText)
        )
      }
      
      return result
    })
    
    // 获取发票类型图标
    const getInvoiceTypeIcon = (type) => {
      const iconMap = {
        'vat-special': 'bill',
        'vat-normal': 'bill-o',
        'electronic': 'peer-pay'
      }
      return iconMap[type] || 'description'
    }
    
    // 切换发票选择状态
    const toggleInvoiceSelection = (id) => {
      // 查找ID在数组中的位置
      const index = selectedInvoiceIds.value.indexOf(id)
      
      // 如果ID不在数组中，添加它；否则，从数组中移除它
      if (index === -1) {
        selectedInvoiceIds.value.push(id)
      } else {
        selectedInvoiceIds.value.splice(index, 1)
      }
      
      // 检查是否应该更新全选状态
      if (filteredInvoices.value.length > 0) {
        selectAll.value = filteredInvoices.value.every(invoice => 
          selectedInvoiceIds.value.includes(invoice.id)
        )
      }
    }
    
    // 确认发票选择
    const confirmInvoiceSelection = () => {
      // 根据选中的ID更新选中的发票列表
      selectedInvoices.value = availableInvoices.value.filter(
        invoice => selectedInvoiceIds.value.includes(invoice.id)
      )
      
      // 将选中的发票ID添加到表单数据
      formData.invoices = selectedInvoiceIds.value
      
      showInvoiceSelector.value = false
      Toast(`已选择${selectedInvoices.value.length}张发票`)
      
      // 自动更新报销金额
      updateExpenseAmountFromInvoices()
    }
    
    // 移除已选择的发票
    const removeSelectedInvoice = (id) => {
      // 从选中列表中移除
      selectedInvoices.value = selectedInvoices.value.filter(invoice => invoice.id !== id)
      
      // 从选中ID中移除
      const index = selectedInvoiceIds.value.indexOf(id)
      if (index !== -1) {
        selectedInvoiceIds.value.splice(index, 1)
      }
      
      // 更新表单数据
      formData.invoices = selectedInvoiceIds.value
      
      // 重新计算金额
      updateExpenseAmountFromInvoices()
    }
    
    // 根据选择的发票更新报销金额
    const updateExpenseAmountFromInvoices = () => {
      if (selectedInvoices.value.length === 0) return
      
      // 重置各项费用金额
      const expenses = {
        transportation: 0,
        accommodation: 0,
        meals: 0,
        others: 0
      }
      
      // 根据发票类型分配金额到相应费用类别
      selectedInvoices.value.forEach(invoice => {
        // 根据发票标题或类型判断费用类别
        if (invoice.title.includes('航空') || invoice.title.includes('机票') || 
            invoice.title.includes('火车') || invoice.title.includes('出租') || 
            invoice.title.includes('交通') || invoice.title.includes('物流')) {
          expenses.transportation += invoice.amount
        } 
        else if (invoice.title.includes('酒店') || invoice.title.includes('住宿') || 
                invoice.title.includes('宾馆')) {
          expenses.accommodation += invoice.amount
        } 
        else if (invoice.title.includes('餐') || invoice.title.includes('食') || 
                invoice.title.includes('饮')) {
          expenses.meals += invoice.amount
        } 
        else {
          expenses.others += invoice.amount
        }
      })
      
      // 更新表单数据
      formData.transportation = expenses.transportation > 0 ? expenses.transportation.toFixed(2) : formData.transportation
      formData.accommodation = expenses.accommodation > 0 ? expenses.accommodation.toFixed(2) : formData.accommodation
      formData.meals = expenses.meals > 0 ? expenses.meals.toFixed(2) : formData.meals
      formData.others = expenses.others > 0 ? expenses.others.toFixed(2) : formData.others
      
      Toast('已根据发票自动分配费用')
    }
    
    // 模拟可选的出差申请数据
    const availableTravels = ref([
      {
        id: 1,
        destination: '上海',
        startDate: '2024-04-15',
        endDate: '2024-04-18',
        reason: '参加医疗器械展会',
        status: 'approved'
      },
      {
        id: 2,
        destination: '北京',
        startDate: '2024-04-05',
        endDate: '2024-04-07',
        reason: '专业培训',
        status: 'approved'
      }
    ])
    
    // 获取选中的出差申请
    const selectedTravel = computed(() => {
      if (!selectedTravelId.value) return null
      return availableTravels.value.find(item => item.id === selectedTravelId.value)
    })
    
    // 计算报销总额
    const totalExpense = computed(() => {
      let total = 0
      if (formData.transportation) total += Number(formData.transportation)
      if (formData.accommodation) total += Number(formData.accommodation)
      if (formData.meals) total += Number(formData.meals)
      if (formData.others) total += Number(formData.others)
      return total.toFixed(2)
    })
    
    // 文件上传前检查
    const beforeRead = (file) => {
      const isImage = file.type.indexOf('image') !== -1
      const isPDF = file.type === 'application/pdf'
      if (!isImage && !isPDF) {
        Toast('请上传图片或PDF格式文件')
        return false
      }
      return true
    }
    
    // 文件上传后处理
    const afterRead = (file) => {
      console.log('File uploaded:', file)
      // 实际项目中应该调用API上传文件到服务器
      // 模拟上传成功
      file.status = 'done'
      file.message = '上传成功'
      // 添加到表单数据
      formData.attachments.push({
        name: file.file.name,
        url: URL.createObjectURL(file.file),
        size: file.file.size
      })
    }
    
    // 删除文件
    const deleteFile = (file) => {
      const index = formData.attachments.findIndex(item => item.url === file.url)
      if (index !== -1) {
        formData.attachments.splice(index, 1)
      }
    }
    
    // 提示信息
    const showTip = (message) => {
      Toast(message)
    }
    
    // 确认选择关联出差
    const confirmTravel = () => {
      if (!selectedTravelId.value) {
        Toast('请选择一个出差申请')
        return
      }
      formData.travelId = selectedTravelId.value
      // 自动填充报销事由
      if (selectedTravel.value && !formData.reason) {
        formData.reason = `${selectedTravel.value.destination}出差报销`
      }
      showTravelPopup.value = false
    }
    
    // 显示费用明细编辑器
    const showExpenseEditor = (type) => {
      currentExpenseType.value = type
      currentExpenseAmount.value = formData[type] || ''
      currentExpenseNote.value = ''
      showExpensePopup.value = true
    }
    
    // 确认费用明细
    const confirmExpense = () => {
      if (!currentExpenseAmount.value) {
        Toast('请输入金额')
        return
      }
      
      formData[currentExpenseType.value] = currentExpenseAmount.value
      showExpensePopup.value = false
    }
    
    // 提交表单
    const onSubmit = () => {
      if (uploadedFiles.value.length === 0) {
        Toast('请上传至少一个报销凭证')
        return
      }
      
      console.log('Submit data:', {
        ...formData,
        totalExpense: totalExpense.value
      })
      
      Toast.success('报销申请提交成功（模拟）')
      setTimeout(() => router.back(), 1500)
    }
    
    const goBack = () => router.back()
    
    // 格式化金额显示
    const formatAmount = (amount) => {
      return parseFloat(amount).toLocaleString('zh-CN', { 
        minimumFractionDigits: 2, 
        maximumFractionDigits: 2 
      })
    }
    
    // 计算已选发票总金额
    const totalSelectedAmount = computed(() => {
      if (selectedInvoiceIds.value.length === 0) return 0
      
      return availableInvoices.value
        .filter(invoice => selectedInvoiceIds.value.includes(invoice.id))
        .reduce((sum, invoice) => sum + invoice.amount, 0)
    })
    
    // 全选/取消全选发票
    const toggleSelectAll = () => {
      if (selectAll.value) {
        // 全选当前过滤后的发票
        selectedInvoiceIds.value = filteredInvoices.value.map(invoice => invoice.id)
      } else {
        // 取消全选
        selectedInvoiceIds.value = []
      }
    }
    
    // 监听过滤条件变化，更新全选状态
    watch([invoiceFilterStatus, invoiceSearchText], () => {
      // 如果过滤条件变化，检查当前是否全选
      if (filteredInvoices.value.length > 0) {
        selectAll.value = filteredInvoices.value.every(invoice => 
          selectedInvoiceIds.value.includes(invoice.id)
        )
      } else {
        selectAll.value = false
      }
    })
    
    // 监听选中状态变化，更新全选复选框
    watch(selectedInvoiceIds, (newIds) => {
      if (filteredInvoices.value.length > 0) {
        selectAll.value = filteredInvoices.value.every(invoice => 
          newIds.includes(invoice.id)
        )
      } else {
        selectAll.value = false
      }
    })
    
    return {
      formData,
      uploadedFiles,
      availableTravels,
      selectedTravelId,
      selectedTravel,
      totalExpense,
      showTravelPopup,
      showExpensePopup,
      currentExpenseType,
      currentExpenseAmount,
      currentExpenseNote,
      beforeRead,
      afterRead,
      deleteFile,
      showTip,
      confirmTravel,
      showExpenseEditor,
      confirmExpense,
      onSubmit,
      goBack,
      showInvoiceSelector,
      invoiceSearchText,
      invoiceFilterStatus,
      selectedInvoiceIds,
      selectedInvoices,
      checkboxRefs,
      invoiceStatusOptions,
      filteredInvoices,
      getInvoiceTypeIcon,
      toggleInvoiceSelection,
      confirmInvoiceSelection,
      removeSelectedInvoice,
      updateExpenseAmountFromInvoices,
      formatAmount,
      totalSelectedAmount,
      toggleSelectAll
    }
  }
}
</script>

<style scoped>
.travel-expense-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.content-area {
  padding: 16px;
}

.expense-amount {
  font-weight: 500;
  color: #1989fa;
}

.upload-tips {
  margin-top: 8px;
  color: #969799;
  font-size: 12px;
  line-height: 1.5;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.popup-title {
  font-size: 16px;
  font-weight: 500;
}

.expense-editor {
  padding: 16px;
}

.popup-footer {
  padding: 16px;
  border-top: 1px solid #ebedf0;
}

.invoice-selector {
  display: flex;
  flex-direction: column;
  margin-bottom: 12px;
}

.selected-invoices {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
}

.invoice-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.invoice-filter {
  padding: 8px 16px;
  border-bottom: 1px solid #ebedf0;
}

.filter-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.invoice-list {
  max-height: 300px;
  overflow-y: auto;
}

.invoice-selection-summary {
  background-color: #f7f8fa;
  padding: 12px 16px;
  border-top: 1px solid #ebedf0;
  font-size: 14px;
}

.summary-content {
  text-align: center;
}

.highlight {
  color: #1989fa;
  font-weight: 500;
}

.invoice-type-icon {
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  color: #1989fa;
}

.invoice-right {
  display: flex;
  align-items: center;
}

.invoice-amount {
  margin-right: 12px;
  font-weight: 500;
  color: #ff976a;
}

.invoice-checkbox-wrapper {
  padding: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.invoice-content {
  display: flex;
  flex-direction: column;
  padding: 4px 0;
  cursor: pointer;
}

.invoice-title {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
}

.invoice-label {
  color: #969799;
  font-size: 12px;
}

.filter-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
  padding: 0 8px;
}

.filter-actions .van-checkbox {
  margin-left: 12px;
}
</style> 